package ve.usb.ddp;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ve.usb.cohesion.runtime.CohesionAction;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import ve.usb.cohesion.runtime.HibernateUtil;
import ve.usb.ddp.hibernate.*;

import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

/**
 * 
 */
public class AccionesCU001ManejoGeneral extends CohesionAction {

    /**
     * Called by Struts for the execution of action A_Pre_ManejoGeneral.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_ManejoGeneral(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_ManejoGeneral",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors encargado_prd, encargado_pas, encargado_paa, encargado_pai, director_DDP
        if (!CohesionActor.checkActor(request, 62)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Pre_PAA.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_PAA(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_PAA",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors encargado_pai, encargado_pas, encargado_paa, encargado_prd, director_DDP
        if (!CohesionActor.checkActor(request, 62)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            /*Empieza nuestro codigo*/
            String query = "SELECT DISTINCT profesor.primerapellido, profesor.segundoapellido, "
                    + "profesor.primernombre, profesor.segundonombre, "
                    + "profesor.ci, profesor.correo, paa.fecha_culminacion "
                    + "FROM \"public\".paa AS paa, \"public\".profesor AS profesor "
                    + "WHERE paa.fecha_culminacion < CURRENT_DATE "
                    + "AND paa.rindio_cuentas = 'false' "
                    + "AND paa.profesor = profesor.idprofesor";
            List<Object[]> resultsQuery = (List<Object[]>) s.createSQLQuery(query).list();
            request.setAttribute("L_ProfesorNoRindioCuentas", resultsQuery);
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Pre_PAS.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_PAS(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_PAS",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors encargado_prd, encargado_pai, encargado_pas, director_DDP, encargado_paa
        if (!CohesionActor.checkActor(request, 62)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            /*Empieza nuestro codigo*/
            String query = "SELECT DISTINCT prof.idprofesor, prof.primernombre,prof.segundonombre, " +
                    "prof.primerapellido, prof.segundoapellido, prof.correo, " +
                    "(monto.fecha_tramite - CURRENT_DATE) AS fechaTramite, prof.ci, (monto.fecha_prox_tramite - CURRENT_DATE) AS fechaProxTramite " +
                    "FROM \"public\".profesor AS prof, \"public\".pas AS pas, \"public\".monto AS monto " +
                    "WHERE prof.idprofesor = pas.profesor " +
                    "AND pas.idpas = monto.pas " +
                    "AND ((monto.fecha_tramite - CURRENT_DATE <= 30 " +
                    "AND 0 <= monto.fecha_tramite - CURRENT_DATE) " +
                    "OR (monto.fecha_prox_tramite - CURRENT_DATE <= 30 " +
                    "AND 0 <= monto.fecha_prox_tramite - CURRENT_DATE))";
            String query2 = "SELECT DISTINCT (monto.fecha_prox_tramite - CURRENT_DATE) AS fechaProxTramite " +
                    "FROM \"public\".profesor AS prof, \"public\".pas AS pas, \"public\".monto AS monto " +
                    "WHERE prof.idprofesor = pas.profesor AND pas.idpas = monto.pas " +
                    "AND ((monto.fecha_tramite - CURRENT_DATE <= 30 " +
                    "AND 0 <= monto.fecha_tramite - CURRENT_DATE) " +
                    "OR (monto.fecha_prox_tramite - CURRENT_DATE <= 30 " +
                    "AND 0 <= monto.fecha_prox_tramite - CURRENT_DATE))";
            List<Integer> result2 = (List<Integer>)s.createSQLQuery(query2).list();
            List<Object[]> result = (List<Object[]>)s.createSQLQuery(query).list();
            List<Object[]> trueResult = new ArrayList<Object[]>();
            for(int i = 0; i<result.size(); i++){
                Object [] object = result.get(i);
                Object[] objectResult = new Object[8];
                objectResult[0] = object[0];
                objectResult[1] = object[1];
                objectResult[2] = object[2];
                objectResult[3] = object[3];
                objectResult[4] = object[4];
                objectResult[5] = object[5];
                objectResult[7] = object[7];
                if(Integer.parseInt(object[6].toString()) > 0){
                    objectResult[6] = object[6];
                    trueResult.add(objectResult);
                }else if(object[8] != null){
                    if(Integer.parseInt(object[8].toString()) > 0){
                        objectResult[6] = object[8];
                        trueResult.add(objectResult);
                    }
                }
            }
            request.getSession().setAttribute("L_ProfesorTram", trueResult);
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Pre_PerfilUsuario.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_PerfilUsuario(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_PerfilUsuario",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors encargado_prd, director_DDP, encargado_pai, encargado_pas, encargado_paa
        if (!CohesionActor.checkActor(request, 62)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            /*Empieza nuestro codigo*/
            F_DatosUsuario fF_DatosUsuario = new F_DatosUsuario();
            Usuario user = (Usuario) request.getSession().getAttribute("u_conectado");
            Usuario activeUser = (Usuario) s.load(Usuario.class, user.getId());
            fF_DatosUsuario.setCorreo(activeUser.getCorreo());
            fF_DatosUsuario.setNombreCompleto(activeUser.getNombreCompleto());
            request.getSession().setAttribute("F_DatosUsuario", fF_DatosUsuario);
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Desconectarse.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Desconectarse(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"A_Pre_Inicio",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors director_DDP, encargado_pas, encargado_pai, encargado_prd, encargado_paa
        if (!CohesionActor.checkActor(request, 62)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            HttpSession httpSess = request.getSession();
            httpSess.invalidate();
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        if (salida == 0) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_Desconectarse.msg0"));
        }

        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_ModificarUsuario.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_ModificarUsuario(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"A_Pre_PerfilUsuario", "A_Pre_PerfilUsuario", "A_Pre_PerfilUsuario",};
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;
        final int SALIDA_2 = 2;

        int salida = SALIDA_0;
//Checking for actors encargado_paa, director_DDP, encargado_prd, encargado_pai, encargado_pas
        if (!CohesionActor.checkActor(request, 62)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            F_DatosUsuario fF_DatosUsuario = (F_DatosUsuario) form;
            /*Empieza nuestro codigo*/
            String nombCompleto = fF_DatosUsuario.getNombreCompleto();
            String email = fF_DatosUsuario.getCorreo();
            String password = fF_DatosUsuario.getNewPassword();
            //Password1 es la contrasena para comparar.
            String password1 = fF_DatosUsuario.getNewPassword1();
            Usuario activeUser = (Usuario) request.getSession().getAttribute("u_conectado");
            activeUser.setNombreCompleto(nombCompleto);
            if (Usuario.emailValido(email)) {
                activeUser.setCorreo(email);
                if (password.equals(password1) && !password.equals("")
                        && !password1.equals("")) {
                    activeUser.setPassword(activeUser.encryptPass(password));
                    s.update(activeUser);
                    s.flush();
                } else if (password.equals(password1) && password.equals("")
                        && password1.equals("")) {
                    s.update(activeUser);
                    s.flush();
                } else {
                    salida = SALIDA_2;
                }
            } else {
                salida = SALIDA_1;
            }
            /*Terminar nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        if (salida == 0) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_ModificarUsuario.msg0"));
        }
        if (salida == 1) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_ModificarUsuario.msg1"));
        }
        if (salida == 2) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_ModificarUsuario.msg2"));
        }

        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Pre_RegistrarUsuario.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_RegistrarUsuario(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_RegistrarUsuario",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors director_DDP
        if (!CohesionActor.checkActor(request, 2)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Pre_ListarUsuarios.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_ListarUsuarios(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_ListarUsuarios",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors director_DDP
        if (!CohesionActor.checkActor(request, 2)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            /*Empieza nuestro codigo*/
            List<Usuario> users = s.createQuery("from Usuario").list();
            request.setAttribute("L_Usuario", users);
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_EliminarUsuarios.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_EliminarUsuarios(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"A_Pre_ListarUsuarios", "A_Pre_ListarUsuarios",};
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;

        int salida = SALIDA_0;
//Checking for actors director_DDP
        if (!CohesionActor.checkActor(request, 2)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            F_EliminarUsuarios fF_EliminarUsuarios = (F_EliminarUsuarios) form;
            /*Empiesa nuestro codigo*/
            String[] eliminados = fF_EliminarUsuarios.getUsuarios_a_eliminar();
            Usuario actualUser = (Usuario) request.getSession().getAttribute("u_conectado");

            List<Usuario> userEliminar;
            for (String login : eliminados) {
                if (login.equals(actualUser.getUser_login())) {
                    salida = SALIDA_1;
                } else {
                    userEliminar = s.createQuery("from Usuario user where user.user_login=:login").setString("login", login).list();
                    s.delete(userEliminar.get(0));
                }
            }
            fF_EliminarUsuarios.reset(mapping, request);
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        if (salida == 0) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_EliminarUsuarios.msg0"));
        }
        if (salida == 1) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_EliminarUsuarios.msg1"));
        }

        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_RegistrarUsuario.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_RegistrarUsuario(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"A_Pre_ManejoGeneral", "A_Pre_RegistrarUsuario", "A_Pre_RegistrarUsuario", "A_Pre_RegistrarUsuario",};
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;
        final int SALIDA_2 = 2;
        final int SALIDA_3 = 3;

        int salida = SALIDA_0;
//Checking for actors director_DDP
        if (!CohesionActor.checkActor(request, 2)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            F_RegistroUsuario fF_RegistroUsuario = (F_RegistroUsuario) form;
            /*Empieza nuestro codigo*/
            String nombCompleto = fF_RegistroUsuario.getNombreCompleto();
            String email = fF_RegistroUsuario.getCorreo();
            String nombUser = fF_RegistroUsuario.getUserLogin();
            Short tipo = fF_RegistroUsuario.getTipoUsuario();
            List<Usuario> users = s.createQuery("from Usuario user where user.user_login=:login").setString("login", nombUser).list();
            Usuario newUser = new Usuario();
            String randomPass = newUser.getRandomPass();
            if (users.isEmpty() && nombCompleto.length() > 0 && email.length() > 0 && tipo != 0
                    && nombUser.length() > 0 && Usuario.emailValido(email)) {
                //Aca agarro el random pass lo encrito y lo seteo en newUser
                newUser.setPassword(newUser.encryptPass(randomPass));
                newUser.setNombreCompleto(nombCompleto);
                newUser.setCorreo(email);
                newUser.setUser_login(nombUser);
                newUser.setTipo(tipo);
                s.save(newUser);
                s.flush();
                fF_RegistroUsuario.reset(mapping, request);
                // TODO Hacer el correo con nuevo password
                String TITULO = "DDP Online: Registro de Usuario";
                String MENSAJE = "Hola " + nombCompleto + ", este correo es confidencial y de uso personal.\n\n";
                MENSAJE += "Tu nombre de usuario es: " + nombUser + "\n";
                MENSAJE += "Tu contraseña es: " + randomPass + "\n\n";
                MENSAJE += "Se recomienda una, vez iniciada la sesión, ir al Perfil de Usuario ";
                MENSAJE += "y modificar su contraseña por alguna mas nemónica para usted.";

                // Enviar el nuevo password al correo
                final String CORREO_REMITENTE = "notificacion.ddp@gmail.com";
                final String PASS_CORREO_REMITENTE = "ddponline";
                // Propiedades de la conexión
                Properties props = new Properties();
                props.setProperty("mail.smtp.host", "smtp.ldc.usb.ve");
                props.setProperty("mail.smtp.starttls.enable", "true");
                // Puerto de gmail para envio de correos
//                props.setProperty("mail.smtp.port", "587");
                // Nombre del usuario
                props.setProperty("mail.smtp.user", CORREO_REMITENTE);
                // Definimos si se requiere o no usuario y password para conectarse
                props.setProperty("mail.smtp.auth", "true");
                // Preparamos la sesion
                javax.mail.Session session = javax.mail.Session.getDefaultInstance(props);
                // Construimos el mensaje
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(CORREO_REMITENTE));
                // Agregamos DESTINATARIO
                message.addRecipients(Message.RecipientType.TO, email);
                // Seteamos ASUNTO
                message.setSubject(TITULO);
                // Agregamos MENSAJE DE TEXTO O HTML
                message.setText(MENSAJE);
                // Especificamos el protocolo a usar, en nuestro caso smtp
                Transport t = session.getTransport("smtp");
                t.connect(CORREO_REMITENTE, PASS_CORREO_REMITENTE);
                //Transport.send(message);
                // Se envia el mensaje a todos lo destinatarios en el array Recipients
                t.sendMessage(message, message.getAllRecipients());
                // Cierre.
                t.close();
            } else if (nombUser.length() == 0) {
                int conteo = users.size() + 1;
                String newNombUser = "Nuevo Usuario N°: " + Integer.toString(conteo);
                //Aca agarro el random pass lo encrito y lo seteo en newUser
                newUser.setPassword(newUser.encryptPass(randomPass));
                newUser.setNombreCompleto(newNombUser);
                newUser.setCorreo(email);
                newUser.setUser_login(nombUser);
                newUser.setTipo(tipo);
                s.save(newUser);
                s.flush();
                fF_RegistroUsuario.reset(mapping, request);
                // TODO Hacer el correo con nuevo password
                String TITULO = "DDP Online: Prueba de envio de correo";
                String MENSAJE = "Hola " + nombCompleto + ", este correo es confidencial y de uso personal.\n\n";
                MENSAJE += "Tu nombre de usuario es: " + nombUser + "\n";
                MENSAJE += "Tu contraseña es: " + randomPass;

                // Enviar el nuevo password al correo
                final String CORREO_REMITENTE = "notificacion.ddp@gmail.com";
                final String PASS_CORREO_REMITENTE = "ddponline";
                // Propiedades de la conexión
                Properties props = new Properties();
                props.setProperty("mail.smtp.host", "smtp.ldc.usb.ve");
                props.setProperty("mail.smtp.starttls.enable", "true");
                // Puerto de gmail para envio de correos
//                props.setProperty("mail.smtp.port", "587");
                // Nombre del usuario
                props.setProperty("mail.smtp.user", CORREO_REMITENTE);
                // Definimos si se requiere o no usuario y password para conectarse
                props.setProperty("mail.smtp.auth", "true");
                // Preparamos la sesion
                javax.mail.Session session = javax.mail.Session.getDefaultInstance(props);
                // Construimos el mensaje
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(CORREO_REMITENTE));
                // Agregamos DESTINATARIO
                message.addRecipients(Message.RecipientType.TO, email);
                // Seteamos ASUNTO
                message.setSubject(TITULO);
                // Agregamos MENSAJE DE TEXTO O HTML
                message.setText(MENSAJE);
                // Especificamos el protocolo a usar, en nuestro caso smtp
                Transport t = session.getTransport("smtp");
                t.connect(CORREO_REMITENTE, PASS_CORREO_REMITENTE);
                //Transport.send(message);
                // Se envia el mensaje a todos lo destinatarios en el array Recipients
                t.sendMessage(message, message.getAllRecipients());
                // Cierre.
                t.close();
            } else if (email.length() == 0 || !Usuario.emailValido(email)) {
                salida = SALIDA_2;
            } else if (!users.isEmpty()) {
                salida = SALIDA_1;
            } else if (tipo == 0) {
                salida = SALIDA_3;
            }
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        if (salida == 0) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_RegistrarUsuario.msg0"));
        }
        if (salida == 1) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_RegistrarUsuario.msg1"));
        }
        if (salida == 2) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_RegistrarUsuario.msg2"));
        }
        if (salida == 3) {
            request.setAttribute("msg",
                    getResources(request).getMessage("A_RegistrarUsuario.msg3"));
        }

        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Pre_PAI.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_PAI(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_PAI",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors encargado_pas, director_DDP, encargado_pai, encargado_prd, encargado_paa
        if (!CohesionActor.checkActor(request, 62)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            /* Empieza codigo propio */
            // Forward del mensaje hacia la vista
            request.setAttribute("msg", request.getAttribute("msg"));
            String query;

            /*******************************************************************
             *                     Alertas de 30 dias Rojo
             ******************************************************************/
            query = "SELECT prof.primerApellido, prof.segundoApellido, "
                    + "prof.primerNombre, prof.segundoNombre, "
                    + "estud.modalidad, (perm.fec_Vencimiento - CURRENT_DATE), "
                    + "prof.correo "
                    + "FROM Profesor prof, Pai pai, "
                    + "    PaiResolucion res1, PaiResolucion res2, "
                    + "    PaiPermisoNoRemunerado perm, PaiEstudio estud "
                    + "WHERE prof.idProfesor = pai.profesor AND "
                    + "    pai.idPai = res1.pai AND pai.idPai = res2.pai AND "
                    + "    res1.idResolucion = perm.resolucion AND "
                    + "    res2.idResolucion = estud.resolucion AND "
                    + //Selecciono el paiActivo
                    "    pai.fec_Ini < CURRENT_DATE AND "
                    + "    pai.fec_Fin > CURRENT_DATE AND "
                    + // Selecciono la ultima resolucion con algun permiso no remunerado asociado
                    "    res1.fec_Resolucion = (SELECT MAX(resAux.fec_Resolucion) "
                    + "                               FROM PaiResolucion resAux, PaiPermisoNoRemunerado permAux "
                    + "                               WHERE pai.idPai = resAux.pai AND "
                    + "                                   resAux.idResolucion = permAux.resolucion"
                    + "                          ) AND "
                    + // Selecciono la ultima resolucion con algun estudio asociado
                    "    res2.fec_Resolucion = (SELECT MAX(resAux.fec_Resolucion) "
                    + "                               FROM PaiResolucion resAux, PaiEstudio estudAux "
                    + "                               WHERE pai.idPai = resAux.pai AND "
                    + "                                   resAux.idResolucion = estudAux.resolucion"
                    + "                          ) AND "
                    + // Selecciono el permiso dentro del rango
                    "    perm.fec_Vencimiento - CURRENT_DATE >= 0 AND "
                    + "    perm.fec_Vencimiento - CURRENT_DATE <= 30 ";
            List list = s.createSQLQuery(query).list();
            list = s.createSQLQuery("SELECT CURRENT_DATE").list();
            request.setAttribute("L_Profesores30", s.createSQLQuery(query).list());


            /*******************************************************************
             *                     Alertas de 60 dias Amarillo                 *
             ******************************************************************/
            query = "SELECT prof.primerApellido, prof.segundoApellido, "
                    + "prof.primerNombre, prof.segundoNombre, "
                    + "estud.modalidad, (perm.fec_Vencimiento - CURRENT_DATE), "
                    + "prof.correo "
                    + "FROM Profesor prof, Pai pai, "
                    + "    PaiResolucion res1, PaiResolucion res2, "
                    + "    PaiPermisoNoRemunerado perm, PaiEstudio estud "
                    + "WHERE prof.idProfesor = pai.profesor AND "
                    + "    pai.idPai = res1.pai AND pai.idPai = res2.pai AND "
                    + "    res1.idResolucion = perm.resolucion AND "
                    + "    res2.idResolucion = estud.resolucion AND "
                    + //Selecciono el paiActivo
                    "    pai.fec_Ini < CURRENT_DATE AND "
                    + "    pai.fec_Fin > CURRENT_DATE AND "
                    + // Selecciono la ultima resolucion con algun permiso no remunerado asociado
                    "    res1.fec_Resolucion = (SELECT MAX(resAux.fec_Resolucion) "
                    + "                               FROM PaiResolucion resAux, PaiPermisoNoRemunerado permAux "
                    + "                               WHERE pai.idPai = resAux.pai AND "
                    + "                                   resAux.idResolucion = permAux.resolucion"
                    + "                          ) AND "
                    + // Selecciono la ultima resolucion con algun estudio asociado
                    "    res2.fec_Resolucion = (SELECT MAX(resAux.fec_Resolucion) "
                    + "                               FROM PaiResolucion resAux, PaiEstudio estudAux "
                    + "                               WHERE pai.idPai = resAux.pai AND "
                    + "                                   resAux.idResolucion = estudAux.resolucion"
                    + "                          ) AND "
                    + // Selecciono el permiso dentro del rango
                    "    perm.fec_Vencimiento - CURRENT_DATE > 30 AND "
                    + "    perm.fec_Vencimiento - CURRENT_DATE <= 60 ";
            request.setAttribute("L_Profesores60", s.createSQLQuery(query).list());


            /*******************************************************************
             *                     Alertas de 90 dias Verde                    *
             ******************************************************************/
            query = "SELECT prof.primerApellido, prof.segundoApellido, "
                    + "prof.primerNombre, prof.segundoNombre, "
                    + "estud.modalidad, (perm.fec_Vencimiento - CURRENT_DATE), "
                    + "prof.correo "
                    + "FROM Profesor prof, Pai pai, "
                    + "    PaiResolucion res1, PaiResolucion res2, "
                    + "    PaiPermisoNoRemunerado perm, PaiEstudio estud "
                    + "WHERE prof.idProfesor = pai.profesor AND "
                    + "    pai.idPai = res1.pai AND pai.idPai = res2.pai AND "
                    + "    res1.idResolucion = perm.resolucion AND "
                    + "    res2.idResolucion = estud.resolucion AND "
                    + //Selecciono el paiActivo
                    "    pai.fec_Ini < CURRENT_DATE AND "
                    + "    pai.fec_Fin > CURRENT_DATE AND "
                    + // Selecciono la ultima resolucion con algun permiso no remunerado asociado
                    "    res1.fec_Resolucion = (SELECT MAX(resAux.fec_Resolucion) "
                    + "                               FROM PaiResolucion resAux, PaiPermisoNoRemunerado permAux "
                    + "                               WHERE pai.idPai = resAux.pai AND "
                    + "                                   resAux.idResolucion = permAux.resolucion"
                    + "                          ) AND "
                    + // Selecciono la ultima resolucion con algun estudio asociado
                    "    res2.fec_Resolucion = (SELECT MAX(resAux.fec_Resolucion) "
                    + "                               FROM PaiResolucion resAux, PaiEstudio estudAux "
                    + "                               WHERE pai.idPai = resAux.pai AND "
                    + "                                   resAux.idResolucion = estudAux.resolucion"
                    + "                          ) AND "
                    + // Selecciono el permiso dentro del rango
                    "    perm.fec_Vencimiento - CURRENT_DATE > 60 AND "
                    + "    perm.fec_Vencimiento - CURRENT_DATE <= 90 ";
            request.setAttribute("L_Profesores90", s.createSQLQuery(query).list());

            /* Termina codigo propio */
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_Pre_EnviarCorreo.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_EnviarCorreo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_EnviarCorreo",};
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
//Checking for actors director_DDP, encargado_pai, encargado_prd, encargado_paa, administrador, encargado_pas
        if (!CohesionActor.checkActor(request, 63)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            /*Comienza nuestro codigo*/
            F_EnviarCorreo fF_EnviarCorreo = new F_EnviarCorreo();
            String destinatario = request.getParameter("destinatario");
            String asunto = request.getParameter("asunto");
            String vengoDe = request.getParameter("vengoDe");

            if (destinatario != null) {
                fF_EnviarCorreo.setDestinatario(destinatario);
            }
            if (asunto != null) {
                fF_EnviarCorreo.setAsunto(asunto);
            }

            request.getSession().setAttribute("F_EnviarCorreo", fF_EnviarCorreo);
            request.getSession().setAttribute("VENGO_ENVIAR_CORREO_DE", vengoDe);
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }

    /**
     * Called by Struts for the execution of action A_EnviarCorreo.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_EnviarCorreo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"A_Pre_PAI", "A_Pre_PAA", "A_Pre_PAS", "V_ListarEstadisticaPAI", "A_Pre_PrincipalEstadisticasPAA", "A_Pre_PrincipalEstadisticasPAS", "V_ConsultaAvanzadaPAI"};
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;
        final int SALIDA_2 = 2;
        final int SALIDA_3 = 3;
        final int SALIDA_4 = 4;
        final int SALIDA_5 = 5;
        final int SALIDA_6 = 6;

        int salida = SALIDA_0;
//Checking for actors director_DDP, encargado_paa, encargado_pai, administrador, encargado_pas, encargado_prd
        if (!CohesionActor.checkActor(request, 63)) {
            return mapping.findForward(CohesionActor.SALIDA_ACTOR);
        }
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            F_EnviarCorreo fF_EnviarCorreo = (F_EnviarCorreo) form;
            /* Empieza nuestro codigo */
            String[] destinatarios = fF_EnviarCorreo.getDestinatario().split(",");
            String asunto = (String) fF_EnviarCorreo.getAsunto();
            String mensaje = (String) fF_EnviarCorreo.getMensaje();
            String vengoDe = (String) request.getSession().getAttribute("VENGO_ENVIAR_CORREO_DE");
            
            //Remitente
            final String CORREO_REMITENTE = "notificacion.ddp@gmail.com";
            final String PASS_CORREO_REMITENTE = "ddponline";

            // Propiedades de la conexión
            Properties props = new Properties();
            props.setProperty("mail.smtp.host", "smtp.ldc.usb.ve");
            props.setProperty("mail.smtp.starttls.enable", "true");
            props.setProperty("mail.smtp.user", CORREO_REMITENTE);
            // Definimos si se requiere o no usuario y password para conectarse
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.ssl.trust", "false");
            // Preparamos la sesion
            javax.mail.Session session = javax.mail.Session.getDefaultInstance(props);

            // Construimos el mensaje
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(CORREO_REMITENTE));
            // Agregamos DESTINATARIO
            for (int i = 0; i < destinatarios.length; i++) {
                message.addRecipients(Message.RecipientType.TO, destinatarios[i]);
            }
            // Seteamos ASUNTO
            message.setSubject(asunto);

            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            // Agregamos MENSAJE DE TEXTO O HTML
            messageBodyPart.setText(mensaje);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Part two is attachment
            if (vengoDe.equals("PAIEstadisticas") || vengoDe.equals("PAAEstadisticas") 
                    || vengoDe.equals("PASEstadisticas") || vengoDe.equals("PAIConsultaAvanzada")) {
                ByteArrayOutputStream baosPDF = (ByteArrayOutputStream) request.getSession().getAttribute("baosPDF");
                String nombrePDF = (String) request.getSession().getAttribute("nombrePDF");
                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(baosPDF.toByteArray(), "application/pdf")));
                messageBodyPart.setFileName(nombrePDF);
                multipart.addBodyPart(messageBodyPart);
            }

            // Put parts in message
            message.setContent(multipart);

            // Especificamos el protocolo a usar, en nuestro caso smtp
            Transport t = session.getTransport("smtp");
            t.connect(CORREO_REMITENTE, PASS_CORREO_REMITENTE);
            //Transport.send(message);
            // Se envia el mensaje a todos lo destinatarios en el array Recipients
            t.sendMessage(message, message.getAllRecipients());
            // Cierre.
            t.close();


            if (vengoDe.equals("PAI")) {
                salida = SALIDA_0;
            } else if (vengoDe.equals("PAA")) {
                salida = SALIDA_1;
            } else if (vengoDe.equals("PAS")) {
                salida = SALIDA_2;
            } else if (vengoDe.equals("PAIEstadisticas")) {
                salida = SALIDA_3;
            } else if (vengoDe.equals("PAAEstadisticas")) {
                salida = SALIDA_4;
            } else if (vengoDe.equals("PASEstadisticas")) {
                salida = SALIDA_5;
            } else if (vengoDe.equals("PAIConsultaAvanzada")) {
                salida = SALIDA_6;
            }

            request.setAttribute("msg", "Correo electrónico enviado con éxito");

            /* Termina nuestro codigo */
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try {
                s.close();
            } catch (Exception ex2) {
            }
        }
        return mapping.findForward(SALIDAS[salida]);
    }
}
